<template>
	<view>
		<view class="content" @touchstart="hideDrawer">
			<scroll-view class="msg-list" scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop"
			 @scrolltoupper="loadHistory" upper-threshold="50">
				<!-- 加载历史数据waitingUI -->
				<view class="cu-load text-gray" v-if="!isGroupJoin"><text class="cuIcon-loading2 cuIconfont-spin"></text>正在加入直播间</view>
				<view class="comment-content">
					<view class="row" v-for="(item,index) in msgList" :key="index" :id="item.ID">
						<block v-if="item.type==MSG_TEXT">
							<view class="text-white blackbg">
								<view class="">
									<text class="s margin-right-xs" v-if="item.from == userInfo.userId">我:</text>
									<text class="s margin-right-xs" v-else>{{item.nick}}:</text>
									<!-- <rich-text :nodes="(item.payload.text)"></rich-text> -->
								</view>
							</view>
						</block>
						<block v-if="item.type=='TIMGroupTipElem'">
							<view class="text-white blackbg" v-if="item.payload.operationType == 1 || item.payload.operationType == 2">
								<view class="">
									<text class="s margin-right-xs" v-if="item.from == userInfo.userId">我 </text>
									<text class="s margin-right-xs" v-else>{{item.nick}} </text>
									<text v-if="item.payload.operationType == 1" class="s">加入直播间</text>
									<text v-else class="s">退出直播间</text>
								</view>
							</view>
						</block>
						<block v-if="item.type=='TIMCustomElem'">
							<view class="text-white blackbg">
								<view class="text-purple2">
									<text class="s margin-right-xs" v-if="item.from == userInfo.userId">我 </text>
									<text class="s margin-right-xs" v-else>{{item.nick}} </text>
									<block v-if="item.payload.data == 'auction'">
										<text>{{item.payload.description}}</text>
									</block>
								</view>
							</view>
						</block>
					</view>
				</view>
			</scroll-view>
		</view>

		<block v-if="autoComment">
			<!-- 抽屉栏 -->
			<view class="popup-layer w100" :class="popupLayerClass" @touchmove.stop.prevent="discard">
				<swiper class="emoji-swiper" :class="{hidden:hideEmoji}" indicator-dots="true" duration="150">
					<swiper-item v-for="(page,pid) in emojiList" :key="pid">
						<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
							<image mode="widthFix" :src="'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/emoji_'+em.url"></image>
						</view>
					</swiper-item>
				</swiper>
				<view class="more-layer" :class="{hidden:hideMore}">
					<view class="list">
						<view class="box" @tap="chooseImage">
							<view class="icon tupian2"></view>
						</view>
						<view class="box" @tap="camera">
							<view class="icon paizhao"></view>
						</view>
						<view class="box" @tap="handRedEnvelopes">
							<view class="icon hongbao"></view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部输入栏 -->
			<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
				<!-- H5下不能录音，输入栏布局改动一下 -->
				<!-- #ifndef H5 -->
				<!-- <view class="voice">
					<view class="icon" :class="isVoice?'jianpan':'yuyin'" @tap="switchVoice"></view>
				</view> -->
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<!-- <view class="more" @tap="showMore">
					<view class="icon add"></view>
				</view> -->
				<!-- #endif -->
				<view class="more" @tap="chooseEmoji">
					<view class="icon biaoqing"></view>
				</view>
				<view class="textbox">
					<view class="voice-mode" :class="[isVoice?'':'hidden',recording?'recording':'']" @touchstart="voiceBegin"
					 @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd" @touchcancel="voiceCancel">{{voiceTis}}</view>
					<view class="text-mode" :class="isVoice?'hidden':''">
						<view class="box">
							<textarea auto-height="true" v-model="textMsg" @focus="textareaFocus" />
							</view>
					</view>
				</view>
			<!-- #ifndef H5 -->
			<!-- <view class="more" @tap="showMore">
					<view class="icon add"></view>
				</view> -->
			<!-- #endif -->
			<view class="send" :class="isVoice?'hidden':''" @tap="sendText">
					<view class="cu-btn bg-green radius shadow">发送</view>
				</view>
			</view>
			<!-- 录音UI效果 -->
			<view class="record" :class="recording?'':'hidden'">
				<view class="ing" :class="willStop?'hidden':''">
					<view class="icon luyin2"></view>
				</view>
				<view class="cancel" :class="willStop?'':'hidden'">
					<view class="icon chehui"></view>
				</view>
				<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
			</view>
			<!-- <view class="windows" :class="windowsState">
				<view class="mask" @touchmove.stop.prevent="discard" @tap="closeRedEnvelope"></view>
				<view class="layer" @touchmove.stop.prevent="discard">
					<view class="open-redenvelope">
						<view class="top">
							<view class="close-btn">
								<view class="icon close" @tap="closeRedEnvelope"></view>
							</view>
						</view>
						<view class="from">来自{{redenvelopeData.from}}</view>
						<view class="blessing">{{redenvelopeData.blessing}}</view>
						<view class="money">{{redenvelopeData.money}}</view>
						<view class="showDetails" @tap="toDetails(redenvelopeData.rid)">
							查看领取详情 <view class="icon to"></view>
						</view>
					</view>
				</view>
				
			</view> -->
		</block>
		<block v-else>
			<view class="cu-modal bottom-modal2 nobg" :class="modalName=='commonModal'?'show':''" @tap="modalName=''">
				<view class="cu-dialog w100" style="border-radius: 0;" @tap.stop="">
					<view class="comment-send-viie space-between padding-xs bg-gray">
						<view class="cuIcon lg cuIcon-emoji margin-right-sm" @tap="chooseEmoji"></view>
						<view class="inps bg-white w100">
							<input name="content" v-model="textMsg" :focus="commentFocus" @blur="commentBlur" class="text-left margin-xs">
						</view>
						<view class="cu-btn bg-green radius margin-left-sm shadow" style="min-width: 120rpx;" @tap="sendText">发送</view>
					</view>
					<swiper class="emoji-swiper" :class="{hidden:hideEmoji}" indicator-dots="true" duration="150">
						<swiper-item v-for="(page,pid) in emojiList" :key="pid">
							<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
								<image mode="widthFix" :src="'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/emoji_'+em.url"></image>
							</view>
						</swiper-item>
					</swiper>
				</view>
			</view>
		</block>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		components: {},
		props: {},
		data() {
			return {
				SDKAppID: 1400398699,
				tls: null,
				userSig: '',
				room_id: '',

				//TIM变量
				conversationActive: null,
				toUserId: '',
				toUserInfo: null,
				userInfo: null,
				nextReqMessageID: '',
				count: 15,
				isCompleted: '',
				msgList: [],
				TIM: null,
				MSG_TEXT: '',
				inputFocus: false,
				memberNum: 0,


				//文字消息
				textMsg: '',
				//消息列表
				isHistoryLoading: false,
				scrollAnimation: false,
				scrollTop: 0,
				scrollToView: '',

				msgImgList: [],
				myuid: 0,

				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				isVoice: false,
				voiceTis: '按住 说话',
				recordTis: "手指上滑 取消发送",
				recording: false,
				willStop: false,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				recordTimer: null,
				recordLength: 0,

				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,

				// 抽屉参数
				popupLayerClass: '',
				// more参数
				hideMore: true,
				//表情定义
				hideEmoji: true,
				emojiList: this.$config.emojiList,
				//表情图片图床名称 ，由于我上传的第三方图床名称会有改变，所以有此数据来做对应，您实际应用中应该不需要

				//红包相关参数
				windowsState: '',
				redenvelopeData: {
					rid: null, //红包ID
					from: null,
					face: null,
					blessing: null,
					money: null
				},
				modalName: '',
				commentFocus: false,//评论焦点
				autoComment: false,//是否默认显示评论
				group: null,//直播间
				actionJoin: false,//是否已经触发加入动作
				isGroupJoin: false,//是否已经加入在直播间
				
			}
		},
		destroyed() {},
		onUnload() {
		},
		created: function(e) {
			this.scrollTop = 9999999
			this.MSG_TEXT = this.$TIM.TYPES.MSG_TEXT
			//语音自然播放结束
			this.AUDIO.onEnded((res) => {
				this.playMsgid = null;
			});
			// #ifndef H5
			//录音开始事件
			this.RECORDER.onStart((e) => {
				this.recordBegin(e);
			})
			//录音结束事件
			this.RECORDER.onStop((e) => {
				this.recordEnd(e);
			})
			// #endif
		},
		computed: {
			...mapState({
				currentMessageList: state => state.currentMessageList,
				isSDKReady: state => state.isSDKReady,
				isTIMLogin: state => state.isTIMLogin,
			})
		},
		watch: {
			currentMessageList(newVal, oldVal) {
				let newone = newVal[newVal.length - 1]
				if(newone && newone.type == 'TIMCustomElem'){
					this.$emit("customElem", newone.payload)
				}
				this.msgList = newVal
				if (newVal && newVal.length > 0) {
					if (newVal[newVal.length - 1].type == 'TIMGroupTipElem' && newVal[newVal.length - 1].payload.memberNum) {
						this.memberNum = newVal[newVal.length - 1].payload.memberNum
						this.$emit("memberChange", this.memberNum)
					}
				}
				this.screenMsg(newVal, oldVal)
			},
			isSDKReady(val) {
				//isSDKReady == true 请求会话列表
				console.log('ready' + val)
				// this.$common.showError('123'+val)
				if (val && this.actionJoin) {
					this.readyJoin()
				}
			},
		},
		methods: {
			...mapMutations(['timLogin', 'timLogout']),
			quit() {
				if(this.group && this.group.ownerID != this.userInfo.userId){
					let promise = this.$tim.tim.quitGroup(this.room_id)
					// this.$common.showError('正在退出')
					if(promise){
						promise.then((imResponse) =>{
							// this.$common.showError('退出成功')
							console.log(imResponse.data.groupID); // 退出成功的群 ID
						}).catch((imError)=> {
							// this.$common.showError('退出失败'+imError)
							console.warn('quitGroup error:', imError); // 退出群组失败的相关信息
						});
					} else {
						// this.$common.showError('退出失败')
					}
					// let promise2 = this.$tim.tim.logout()
					// if (promise2) {
					// 	promise2.then((imResponse) => {
					// 		console.log(imResponse.data); // 登出成功
					// 		this.$store.commit('timLogout')
					// 	}).catch((imError) => {
					// 		console.warn('logout error:', imError);
					// 	});
					// }
				}
			},
			join(userInfo, room_id, autoComment) {
				if(autoComment) this.autoComment = autoComment
				this.userInfo = userInfo
				this.room_id = room_id
				this.actionJoin = true

				this.$store.commit('createGroupConversationActive', room_id)

				if (!this.isTIMLogin) {
					let genUserSig = this.$tim.genTestUserSig(this.userInfo.userId)
					let promise = this.$tim.tim.login({
						userID: this.userInfo.userId,
						userSig: genUserSig.userSig
					})
					// this.$common.showError('im登录中')
					if(promise){
						promise.then((res) => {
							this.$store.commit("toggleIsLogin", true);
							this.timLogin(true)
							// this.$common.showError('im登录成功')
							
							if (this.isSDKReady) {
								this.readyJoin()
							} 
						}).catch((err) => {
							console.warn('login error:', err); // 登录失败的相关信息
						});
					} else {
						// this.$common.showError('im登录失败，稍后重新再试')
					}
					return
				}
				// this.$common.showError(this.isTIMLogin+'--'+this.isSDKReady)
				if (this.isSDKReady) {
					this.readyJoin()
				}
				// console.log(this.isTIMLogin)
				// console.log(this.isSDKReady)
			},
			updateUser() {
				// console.log(this.$tim.tim)
				// let promise = this.$tim.tim.getMyProfile();
				// promise.then(function(imResponse) {
				// 	console.log(imResponse.data); // 个人资料 - Profile 实例
				// }).catch(function(imError) {
				// 	console.warn('getMyProfile error:', imError); // 获取个人资料失败的相关信息
				// });
				this.$common.getMember().then((member) => {
					console.log(23)
					let promise = this.$tim.tim.updateMyProfile({
						nick: member.nickname,
						avatar: member.head_portrait,
						gender: this.$TIM.TYPES.GENDER_UNKNOWN,
						selfSignature: member.realname,
						allowType: this.$TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
					});
					console.log(promise)
					if(promise){
						promise.then((imResponse)=> {
							console.log(imResponse)
							// this.$common.showError('更新资料成功')
						}).catch((imError) => {
							console.log(imError)
							// this.$common.showError('更新资料失败')
						});
					} else{
						// this.$common.showError('更新资料失败2')
						setTimeout((r)=>{this.updateUser()}, 500)
					}
				}).catch((e)=>{
					console.log(e)
				})
			},
			readyJoin() {
				console.log('readyjoin')
				this.updateUser()
				this.timSearchGroup()
			},
			timSearchGroup() {
				let promise = this.$tim.tim.searchGroupByID(this.room_id)
				
				// this.$common.showError('正在加入直播间')
				
				if(promise){
					promise.then((imResponse) => {
						this.group = imResponse.data.group
						console.log(this.group)
						this.timJoinGroup()
					}).catch((imError) => {
						console.log(imError)
						this.timCreateGroup()
					});
				} else {
					setTimeout((r)=>{
						this.timSearchGroup()
					},500)
					// this.$common.showError(this.isSDKReady+'查找直播间失败2'+this.room_id + this.isTIMLogin)
				}
			},
			timJoinGroup() {
				let promise = this.$tim.tim.joinGroup({
					groupID: this.room_id,
					type: this.$TIM.TYPES.GRP_AVCHATROOM
				})

				if(promise){
					promise.then((res) => {
						// this.$common.showError('加入直播间成功')
						// this.getMsgList()
						this.isGroupJoin = true
					}).catch((err) => {
						// this.$common.showError('加入直播间失败')
						console.warn('timJoinGroup error:', err); // 登录失败的相关信息
					});
				} 
				// else this.$common.showError('加入直播间失败2')
			},
			timCreateGroup() {
				let promise = this.$tim.tim.createGroup({
					name: this.room_id,
					groupID: this.room_id,
					joinOption: this.$TIM.JOIN_OPTIONS_FREE_ACCESS,
					type: this.$TIM.TYPES.GRP_AVCHATROOM,
					memberList: [{
						userID: this.userInfo.userId
					}] // 如果填写了 memberList，则必须填写 userID
				})
				if(promise){
					promise.then((res) => {
						console.log(res)
						// this.$common.showError('创建直播间成功')
						this.timJoinGroup()
					}).catch((err) => {
						// this.$common.showError('创建直播间失败')
						console.warn('timJoinGroup error:', err); // 登录失败的相关信息
					});
				} 
				// else this.$common.showError('创建直播间失败2')
			},


			//聊天的节点加上外层的div
			nodesFliter(str) {
				let nodeStr = '<div style="align-items: center;word-wrap:break-word;display:inline;">' + str + '</div>'
				return nodeStr
			},
			//时间过滤
			timeFliter(timer) {
				// let timeData = new Date(timer*1000)
				let str = this.$common.timeFormat(timer)
				return str
			},
			// 接受消息(定位消息)
			screenMsg(newVal, oldVal) {
				if (newVal[0] && oldVal[0] && newVal[0].ID && oldVal[0].ID) {
					if (newVal[0].ID != oldVal[0].ID && newVal.length >= this.count) {
						this.$nextTick(() => {
							this.scrollToView = oldVal[0].ID
							this.scrollToBottom()
						});
					} else {
						this.$nextTick(() => {
							this.scrollToView = newVal[newVal.length - 1].ID
							this.scrollToBottom()
						});
					}
				} else {
					if (newVal[0]) {
						console.log(newVal[newVal.length - 1].ID)
						this.$nextTick(() => {
							this.scrollToView = newVal[newVal.length - 1].ID
							this.scrollToBottom()
						});
					}
				}
			},
			//触发滑动到顶部(加载历史信息记录)
			loadHistory(e) {
				// 更多消息列表
				let promise = this.$tim.tim.getMessageList({
					conversationID: 'GROUP' + this.room_id,
					nextReqMessageID: this.nextReqMessageID,
					count: this.count
				});
				promise.then((res) => {
					this.$store.commit('unshiftCurrentMessageList', res.data.messageList)
					this.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
					this.isCompleted = res.data.isCompleted

				});
				//这段代码很重要，不然每次加载历史数据都会跳到顶部
				this.$nextTick(function() {
					this.scrollToView = this.nextReqMessageID; //跳转上次的第一行信息位置
					this.scrollToBottom()
					this.$nextTick(function() {
						this.scrollAnimation = true; //恢复滚动动画
					});

				});
				this.isHistoryLoading = false;
			},
			// 加载初始页面消息
			getMsgList() {
				// 历史消息列表
				let promise = this.$tim.tim.getMessageList({
					conversationID: 'GROUP' + this.room_id,
					count: this.count
				});
				promise.then((res) => {
					console.log(res)
					if (res.data.messageList[0]) {
						this.$store.commit('pushCurrentMessageList', res.data.messageList)
						this.nextReqMessageID = res.data.nextReqMessageID // 用于续拉，分页续拉时需传入该字段。
						this.isCompleted = res.data.isCompleted
						this.scrollToView = res.data.messageList[res.data.messageList.length - 1].ID
						this.scrollToBottom()
						console.log(this.nextReqMessageID)
					}
				});
				// 滚动到底部
				this.$nextTick(function() {
					//进入页面滚动到底部
					this.scrollTop = 9999;
					this.$nextTick(function() {
						this.scrollAnimation = true;
					});
				});
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(content) {
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350); //350是定义消息图片最大宽度
				let maxH = uni.upx2px(350); //350是定义消息图片最大高度
				if (content.w > maxW || content.h > maxH) {
					let scale = content.w / content.h;
					content.w = scale > 1 ? maxW : maxH * scale;
					content.h = scale > 1 ? maxW / scale : maxH;
				}
				return content;
			},
			//更多功能(点击+弹出)
			showMore() {
				this.isVoice = false;
				this.hideEmoji = true;
				if (this.hideMore) {
					this.hideMore = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			// 打开抽屉
			openDrawer() {
				this.popupLayerClass = 'showLayer';
			},
			// 隐藏抽屉
			hideDrawer() {
				this.popupLayerClass = '';
				setTimeout(() => {
					this.hideMore = true;
					this.hideEmoji = true;
				}, 150);
			},
			// 选择图片发送
			chooseImage() {
				this.getImage('album');
			},
			//拍照发送
			camera() {
				this.getImage('camera');
			},
			//发红包
			handRedEnvelopes() {
				uni.navigateTo({
					url: 'HM-hand/HM-hand'
				});
				this.hideDrawer();
			},
			//选照片 or 拍照
			getImage(type) {
				this.hideDrawer();
				uni.chooseImage({
					sourceType: [type],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: (image) => {
									console.log(image.width);
									console.log(image.height);
									let msg = {
										url: res.tempFilePaths[i],
										w: image.width,
										h: image.height
									};
									this.sendMsg(msg, 'img');
								}
							});
						}
					}
				});
			},
			// 选择表情
			chooseEmoji() {
				this.hideMore = true;
				if (this.hideEmoji) {
					this.hideEmoji = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			//添加表情
			addEmoji(em) {
				this.textMsg += em.alt;
			},

			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus() {
				if (this.popupLayerClass == 'showLayer' && this.hideMore == false) {
					this.hideDrawer();
				}
			},
			// 发送文字消息
			sendText() {
				this.hideDrawer(); //隐藏抽屉
				if (!this.textMsg) {
					return;
				}
				let content = this.replaceEmoji(this.textMsg);
				let msg = {
					text: content
				}
				this.sendMsg(msg, 'text');
				this.textMsg = ''; //清空输入框
			},
			//替换表情符号为图片
			replaceEmoji(str) {
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
					console.log("item: " + item);
					for (let i = 0; i < this.emojiList.length; i++) {
						let row = this.emojiList[i];
						for (let j = 0; j < row.length; j++) {
							let EM = row[j];
							if (EM.alt == item) {
								//在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径 
								//比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
								let onlinePath = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/emoji_'
								let imgstr = '<img src="' + onlinePath + EM.url + '"  style="width:25px;height:25px;">';
								return imgstr;
							}
						}
					}
				});
				return replacedStr;
			},
			commentBlur() {
				this.commentFocus = false
				window.scroll(0, 0)
			},
			showCommon() {
				this.commentFocus = true
				this.modalName = 'commonModal'
			},
			//发送自定义事件
			sendCustomMsg(type, desc, content){
				console.log(type)
				let message = this.$tim.tim.createCustomMessage({
					to: this.room_id,
					conversationType: this.$TIM.TYPES.CONV_GROUP,
					payload: {
						data: type, // 用于标识该消息是骰子类型消息
						description: desc, // 获取骰子点数
						extension: content
					}
				});
				this.$store.commit('pushCurrentMessageList', message)
				let pomise = this.$tim.tim.sendMessage(message)
				// pomise.then(res => {
				// 	console.log(res)
				// 	this.$nextTick(() => {
				// 		// 滚动到底
				// 		this.scrollToView = res.data.message.ID
				// 		this.scrollToBottom()
				// 	});
				// 	this.commentFocus = false
				// 	this.modalName = ''
				// })
				return pomise
			},
			// 发送消息
			sendMsg(content, type) {
				console.log(content)
				let message = this.$tim.tim.createTextMessage({
					to: this.room_id,
					conversationType: this.$TIM.TYPES.CONV_GROUP,
					payload: {
						text: content.text
					}
				});
				this.$store.commit('pushCurrentMessageList', message)
				let pomise = this.$tim.tim.sendMessage(message)
				pomise.then(res => {
					console.log(res)
					this.$nextTick(() => {
						// 滚动到底
						this.scrollToView = res.data.message.ID
						this.scrollToBottom()
					});
					this.commentFocus = false
					this.modalName = ''
				})
			},
			// 添加文字消息到列表
			addTextMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加语音消息到列表
			addVoiceMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加图片消息到列表
			addImgMsg(msg) {
				msg.msg.content = this.setPicSize(msg.msg.content);
				this.msgImgList.push(msg.msg.content.url);
				this.msgList.push(msg);
			},
			addRedEnvelopeMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加系统文字消息到列表
			addSystemTextMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加系统红包消息到列表
			addSystemRedEnvelopeMsg(msg) {
				this.msgList.push(msg);
			},
			// 打开红包
			openRedEnvelope(msg, index) {
				let rid = msg.content.rid;
				uni.showLoading({
					title: '加载中...'
				});
				console.log("index: " + index);
				//模拟请求服务器效果
				setTimeout(() => {
					//加载数据
					if (rid == 0) {
						this.redenvelopeData = {
							rid: 0, //红包ID
							from: "大黑哥",
							face: "/static/img/im/face/face.jpg",
							blessing: "恭喜发财，大吉大利",
							money: "已领完"
						}
					} else {
						this.redenvelopeData = {
							rid: 1, //红包ID
							from: "售后客服008",
							face: "/static/img/im/face/face_2.jpg",
							blessing: "恭喜发财",
							money: "0.01"
						}
						if (!msg.content.isReceived) {
							// {type:"system",msg:{id:8,type:"redEnvelope",content:{text:"你领取了售后客服008的红包"}}},
							this.sendSystemMsg({
								text: "你领取了" + (msg.userinfo.uid == this.myuid ? "自己" : msg.userinfo.username) + "的红包"
							}, 'redEnvelope');
							console.log("this.msgList[index]: " + JSON.stringify(this.msgList[index]));
							this.msgList[index].msg.content.isReceived = true;
						}
					}
					uni.hideLoading();
					this.windowsState = 'show';

				}, 200)
			},

			// 关闭红包弹窗
			closeRedEnvelope() {
				this.windowsState = 'hide';
				setTimeout(() => {
					this.windowsState = '';
				}, 200)
			},
			sendSystemMsg(content, type) {
				let lastid = this.msgList[this.msgList.length - 1].msg.id;
				lastid++;
				let row = {
					type: "system",
					msg: {
						id: lastid,
						type: type,
						content: content
					}
				};
				this.screenMsg(row)
			},
			//领取详情
			toDetails(rid) {
				uni.navigateTo({
					url: 'HM-details/HM-details?rid=' + rid
				})
			},
			// 预览图片
			showPic(msg) {
				uni.previewImage({
					indicator: "none",
					current: msg.content.url,
					urls: this.msgImgList
				});
			},
			// 播放语音
			playVoice(msg) {
				this.playMsgid = msg.id;
				this.AUDIO.src = msg.content.url;
				this.$nextTick(function() {
					this.AUDIO.play();
				});
			},
			// 录音开始
			voiceBegin(e) {
				if (e.touches.length > 1) {
					return;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({
					format: "mp3"
				}); //录音开始,
			},
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true;
				this.voiceTis = '松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000)
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			// 结束录音
			voiceEnd(e) {
				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop(); //录音结束
			},
			//录音结束(回调文件)
			recordEnd(e) {
				clearInterval(this.recordTimer);
				if (!this.willStop) {
					console.log("e: " + JSON.stringify(e));
					let msg = {
						length: 0,
						url: e.tempFilePath
					}
					let min = parseInt(this.recordLength / 60);
					let sec = this.recordLength % 60;
					min = min < 10 ? '0' + min : min;
					sec = sec < 10 ? '0' + sec : sec;
					msg.length = min + ':' + sec;
					this.sendMsg(msg, 'voice');
				} else {
					console.log('取消发送录音');
				}
				this.willStop = false;
			},
			// 切换语音/文字输入
			switchVoice() {
				this.hideDrawer();
				this.isVoice = this.isVoice ? false : true;
			},
			discard() {
				return;
			},
			scrollToBottom: function() {
				let query = uni.createSelectorQuery()
				query.in(this).select('.comment-content').boundingClientRect()
				query.exec((res) => {
					this.scrollTop = res[0].height
				})
			},
		},
	}
</script>

<style lang="scss">
	// @import "@/common/tim/static/HM-chat/css/style.scss";
</style>
